package com.jacobson.huobi.websocket

import com.jacobson.core.widget.logger.LoggerFactory
import com.jacobson.huobi.Constants
import com.jacobson.huobi.common.expansion.toJson
import com.jacobson.huobi.entities.websocket.Protocol
import com.jacobson.huobi.entities.websocket.RefreshSymbolAction
import org.java_websocket.client.WebSocketClient
import org.java_websocket.handshake.ServerHandshake
import java.net.URI

class WebsocketClient : WebSocketClient(URI(Constants.URL_WEBSOCKET)) {
    private val logger = LoggerFactory.getLogger()

    override fun onOpen(handshakedata: ServerHandshake) {
        logger.d("Websocket onOpen >> $this >> ${Constants.URL_WEBSOCKET}")
        WebsocketManager.sendMessage(ProtocolFactory.ofRefreshSymbolAction("huobi","1"))
    }

    override fun onClose(code: Int, reason: String?, remote: Boolean) {
        logger.w("Websocket onClose($code) --> $reason  >>> $remote >> ${Constants.URL_WEBSOCKET}")
    }

    override fun onMessage(message: String) {
        WebsocketMessageDispatcher.dispatchWebsocketMessage(message)
    }

    override fun onError(ex: Exception) {
        ex.printStackTrace()
    }

    fun sendProtocol(protocol: Protocol) {
        logger.v("发送消息：${protocol.value} >> $isOpen")
        if (isOpen) {
            send(protocol.toJson())
        }
    }

}